import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'product_detail_state.dart';
import '../../../core/repository/default_api.dart';
import '../../../core/config/api_config.dart';
import '../../../gen/assets.gen.dart';

class ProductDetailLogic extends GetxController {
  final state = ProductDetailState();
  final _api = DefaultApi();

  @override
  void onInit() {
    super.onInit();
    // 获取传递的商品ID
    final args = Get.arguments as Map<String, dynamic>?;
    if (args != null && args['productId'] != null) {
      _loadProductDetail(args['productId']);
    }
  }

  /// 加载商品详情
  Future<void> _loadProductDetail(int productId) async {
    try {
      final response = await _api.queryShopProductDetailGet<Map<String, dynamic>>(
        id: productId,
        isShowLoading: true,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null) {
          state.productDetail.value = data;
          
          // 处理图片URL列表
          if (data['imageUrl'] != null && data['imageUrl'].toString().isNotEmpty) {
            final images = data['imageUrl'].toString().split(',');
            state.imageUrls.value = images.map((url) {
              final trimmedUrl = url.trim();
              if (!trimmedUrl.startsWith('http')) {
                return '${ApiConfig.baseUrl}$trimmedUrl';
              }
              return trimmedUrl;
            }).toList();
          }
        }
      }
    } catch (e) {
      Toast.show('加载商品详情失败');
    }
  }

  /// 获取地址列表
  Future<List<Map<String, dynamic>>> _getAddressList() async {
    try {
      final response = await _api.queryShippingAddressListGet<Map<String, dynamic>>();
      
      if (response != null && response['code'] == 200) {
        final List<dynamic> data = response['data'] ?? [];
        return data.map((item) {
          final isDefaultValue = item['isDefault'];
          final isDefault = isDefaultValue == 1;
          
          return {
            'id': item['id'],
            'name': item['recipientName'],
            'phone': item['recipientPhone'],
            'isDefault': isDefault,
            'address': '${item['province']}${item['city']}${item['district']}${item['detailedAddress']}',
            'province': item['province'],
            'city': item['city'],
            'district': item['district'],
            'detailedAddress': item['detailedAddress'],
          };
        }).toList();
      }
      return [];
    } catch (e) {
      return [];
    }
  }

  /// 立即兑换
  Future<void> onExchange() async {
    final product = state.productDetail.value;
    if (product == null) return;

    // 获取地址列表
    final addressList = await _getAddressList();
    
    // 无论有没有地址，都显示兑换弹窗
    final selectedAddress = addressList.isNotEmpty 
        ? _getDefaultOrFirstAddress(addressList) 
        : null;
    _showExchangeDialog(product, selectedAddress, addressList);
  }

  /// 获取默认地址或第一个地址
  Map<String, dynamic>? _getDefaultOrFirstAddress(List<Map<String, dynamic>> addressList) {
    if (addressList.isEmpty) return null;
    
    // 查找默认地址
    final defaultAddress = addressList.firstWhere(
      (addr) => addr['isDefault'] == true,
      orElse: () => addressList.first,
    );
    return defaultAddress;
  }

  /// 显示兑换确认弹窗
  void _showExchangeDialog(
    Map<String, dynamic> product,
    Map<String, dynamic>? selectedAddress,
    List<Map<String, dynamic>> addressList,
  ) {
    final currentAddress = Rxn<Map<String, dynamic>>(selectedAddress);
    final remarkController = TextEditingController();

    Get.dialog(
      Dialog(
        backgroundColor: Colors.transparent,
        child: Container(
          width: 358.w,
          decoration: BoxDecoration(
            color: const Color(0xFF282725),
            borderRadius: BorderRadius.circular(24.r),
          ),
          child: Padding(
            padding: EdgeInsets.all(24.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                // 关闭按钮
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    GestureDetector(
                      onTap: () => Get.back(),
                      child: Icon(
                        Icons.close,
                        color: Colors.white,
                        size: 24.sp,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 16.h),
                // 商品信息
                Row(
                  children: [
                    Container(
                      width: 80.w,
                      height: 80.w,
                      decoration: BoxDecoration(
                        color: Colors.grey[800],
                        borderRadius: BorderRadius.circular(8.r),
                      ),
                      child: state.imageUrls.isNotEmpty
                          ? ClipRRect(
                              borderRadius: BorderRadius.circular(8.r),
                              child: Image.network(
                                state.imageUrls.first,
                                fit: BoxFit.cover,
                                loadingBuilder: (context, child, loadingProgress) {
                                  if (loadingProgress == null) return child;
                                  return Center(
                                    child: CircularProgressIndicator(
                                      value: loadingProgress.expectedTotalBytes != null
                                          ? loadingProgress.cumulativeBytesLoaded /
                                              loadingProgress.expectedTotalBytes!
                                          : null,
                                      strokeWidth: 2,
                                      valueColor: const AlwaysStoppedAnimation<Color>(
                                        Color(0xFFF67F41),
                                      ),
                                    ),
                                  );
                                },
                                errorBuilder: (context, error, stackTrace) {
                                  return Center(
                                    child: Icon(
                                      Icons.broken_image,
                                      color: Colors.grey[600],
                                      size: 40.sp,
                                    ),
                                  );
                                },
                              ),
                            )
                          : Icon(
                              Icons.image,
                              color: Colors.grey[600],
                              size: 40.sp,
                            ),
                    ),
                    SizedBox(width: 12.w),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            product['name'] ?? '',
                            style: TextStyle(
                              fontSize: 16.sp,
                              color: Colors.white,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          SizedBox(height: 8.h),
                          Text(
                            'X1',
                            style: TextStyle(
                              fontSize: 14.sp,
                              color: Colors.grey[400],
                            ),
                          ),
                        ],
                      ),
                    ),
                    Text(
                      '实付：${product['pointsPrice']}积分',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: const Color(0xFFF67F41),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 24.h),
                // 收货地址
                Obx(() {
                  final address = currentAddress.value;
                  final hasAddress = address != null;
                  
                  return GestureDetector(
                    onTap: () async {
                      // 直接跳转到地址页面
                      Get.back(); // 先关闭兑换弹窗
                      final result = await Get.toNamed('/shipping-address');
                      // 如果从地址页面返回，重新获取地址并显示弹窗
                      if (result == true) {
                        onExchange();
                      }
                    },
                    child: Container(
                      padding: EdgeInsets.all(16.w),
                      decoration: BoxDecoration(
                        border: Border.all(
          color: const Color(0xff3A3A3A),
          width: 1,
        ),
                        borderRadius: BorderRadius.circular(12.r),
                      ),
                      child: Row(
                        children: [
                          Expanded(
                            child: hasAddress
                                ? Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Row(
                                        children: [
                                          Text(
                                            address['name'] ?? '',
                                            style: TextStyle(
                                              fontSize: 16.sp,
                                              color: Colors.white,
                                              fontWeight: FontWeight.w500,
                                            ),
                                          ),
                                          SizedBox(width: 12.w),
                                          Text(
                                            address['phone'] ?? '',
                                            style: TextStyle(
                                              fontSize: 14.sp,
                                              color: Colors.white,
                                            ),
                                          ),
                                          if (address['isDefault'] == true) ...[
                                            SizedBox(width: 8.w),
                                            Container(
                                              padding: EdgeInsets.symmetric(
                                                horizontal: 6.w,
                                                vertical: 2.h,
                                              ),
                                              decoration: BoxDecoration(
                                                color: const Color(0xFFF67F41),
                                                borderRadius: BorderRadius.circular(4.r),
                                              ),
                                              child: Text(
                                                '默认',
                                                style: TextStyle(
                                                  fontSize: 10.sp,
                                                  color: Colors.white,
                                                ),
                                              ),
                                            ),
                                          ],
                                        ],
                                      ),
                                      SizedBox(height: 8.h),
                                      Text(
                                        address['address'] ?? '',
                                        style: TextStyle(
                                          fontSize: 14.sp,
                                          color: Colors.grey[400],
                                        ),
                                        maxLines: 2,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ],
                                  )
                                : Text(
                                    '暂无收货地址，去添加',
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      color: const Color(0xFFF67F41),
                                    ),
                                  ),
                          ),
                          Icon(
                            Icons.arrow_forward_ios,
                            color: Colors.grey[500],
                            size: 16.sp,
                          ),
                        ],
                      ),
                    ),
                  );
                }),
                SizedBox(height: 16.h),
                // 备注输入框
                Container(
                  padding: EdgeInsets.all(16.w),
                 decoration: BoxDecoration(
                        border: Border.all(
          color: const Color(0xff3A3A3A),
          width: 1,
        ),
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  child: TextField(
                    controller: remarkController,
                    maxLines: 3,
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.white,
                    ),
                    decoration: InputDecoration(
                      hintText: '输入备注...',
                      hintStyle: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[600],
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.zero,
                      isDense: true,
                    ),
                  ),
                ),
                SizedBox(height: 24.h),
                // 确认兑换按钮
                Obx(() {
                  final hasAddress = currentAddress.value != null;
                  
                  return GestureDetector(
                    onTap: () {
                      if (!hasAddress) {
                        Toast.show('请先选择收货地址');
                        return;
                      }
                      
                      exchangeProduct(
                        productsId: product['id'].toString(),
                        addressId: currentAddress.value!['id'].toString(),
                        productCount: '1',
                      );
                    },
                    child: Container(
                      width: double.infinity,
                      padding: EdgeInsets.symmetric(vertical: 16.h),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: hasAddress
                              ? [const Color(0xFFFF6B35), const Color(0xFFF67F41)]
                              : [Colors.grey[700]!, Colors.grey[700]!],
                        ),
                        borderRadius: BorderRadius.circular(24.r),
                      ),
                      child: Text(
                        '确认兑换',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  );
                }),
              ],
            ),
          ),
        ),
      ),
    );
  }



  /// 兑换商品
  Future<void> exchangeProduct({
    required String productsId,
    required String addressId,
    required String productCount,
  }) async {
    try {
      final response = await _api.exchangeProductPost<Map<String, dynamic>>(
        productsId: productsId,
        addressId: addressId,
        productCount: productCount,
        isShowLoading: true,
      );

      if (response != null && response['code'] == 200) {
        Get.back(); // 关闭兑换弹窗
        // 显示兑换成功弹窗
        final orderData = response['data'];
        _showExchangeSuccessDialog(orderData);
      } else {
        Toast.show(response?['msg'] ?? '兑换失败');
      }
    } catch (e) {
      Toast.show('兑换失败，请稍后重试');
    }
  }

  /// 显示兑换成功弹窗
  void _showExchangeSuccessDialog(Map<String, dynamic>? orderData) {
    Get.dialog(
      Dialog(
        backgroundColor: Colors.transparent,
        child: Container(
          width: 358.w,
          height: 450.h,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(Assets.points.exchangeDialogBg.path),
              fit: BoxFit.cover,
            ),
            borderRadius: BorderRadius.circular(24.r),
          ),
          child: Stack(
            children: [
              // 兑换成功文字
              Positioned(
                left: 0,
                right: 0,
                top: 280.h,
                child: Text(
                  '兑换成功',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 24.sp,
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                  ),
                ),
              ),
              // 按钮区域
              Positioned(
                left: 24.w,
                right: 24.w,
                bottom: 40.h,
                child: Row(
                  children: [
                    // 继续兑换按钮
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          Get.back(); // 关闭成功弹窗
                          // 重新显示兑换弹窗
                          onExchange();
                        },
                        child: Container(
                          height: 54.h,
                          decoration: BoxDecoration(
                            color: const Color(0xFF141414),
                            borderRadius: BorderRadius.circular(40.r),
                            border: Border.all(
                              color: const Color(0xFF444444),
                              width: 1,
                            ),
                          ),
                          child: Center(
                            child: Text(
                              '继续兑换',
                              style: TextStyle(
                                fontSize: 16.sp,
                                color: Colors.white,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: 12.w),
                    // 查看订单按钮
                    Expanded(
                      child: GestureDetector(
                        onTap: () async {
                          Get.back(); // 关闭成功弹窗
                          // 跳转到订单详情页面
                          if (orderData != null && orderData['id'] != null) {
                            try {
                              final response = await _api.queryShopPointsOrderDetailGet<Map<String, dynamic>>(
                                id: orderData['id'],
                                isShowLoading: true,
                              );
                              
                              if (response != null && response['code'] == 200) {
                                final detailData = response['data'];
                                Get.toNamed('/logistics-detail', arguments: detailData);
                              }
                            } catch (e) {
                              Toast.show('加载订单详情失败');
                            }
                          }
                        },
                        child: Container(
                          height: 54.h,
                          decoration: BoxDecoration(
                            color: const Color(0xFFFDFDFD),
                            borderRadius: BorderRadius.circular(40.r),
                          ),
                          child: Center(
                            child: Text(
                              '查看订单',
                              style: TextStyle(
                                fontSize: 16.sp,
                                color: Colors.black,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
      barrierDismissible: false, // 不允许点击外部关闭
    );
  }
}
